import { StyleSheet, 
  ImageBackground, 
  Text, 
  FlatList,
  ToastAndroid,
  BackHandler,
  View, 
  Image,
  Button,
  Modal,
  TextInput,
  ScrollView,
  TouchableOpacity
} from 'react-native';
import React, { useState,useEffect } from 'react';

const Bg = (props)=>{
  return (
    <View style={props.style}>
      <Image 
        resizeMode={props.resizeMode}
        source={props.source}
        style={{
          position:'absolute',
          width: '100%',
          height: '100%'
        }}
      />
      {props.children}
    </View>
  )
}
let page = 1;
let now = 0;
export default function App() {
  const [topics,setTopics] = useState([]);
  const [refresh,setRefresh] = useState(false);
  const [show,setShow] = useState(false);
  const getTopics = (page)=>{
    fetch('https://cnodejs.org/api/v1/topics?page='+page)
      .then(res=>res.json())
      .then(res=>{
        setTopics([...topics,...res.data]);
      })
  }
  useEffect(()=>{
    getTopics(1);
    BackHandler.addEventListener(
      'hardwareBackPress',
      ()=>{
        if(Date.now()-now>2000){
          now = Date.now();
          ToastAndroid.show('确定要退出吗',ToastAndroid.SHORT)
          return true;
        }else{
          BackHandler.exitApp()
        }
      }
    )
  },[])
  return (
    <View style={[styles.container]}>
      <Button 
        title='显示Modal'
        onPress={()=>{setShow(true)}}
      />
      <Button 
        title='显示Modal'
        onPress={()=>{setShow(true)}}
      />
      <Modal
        animationType="slide"
        transparent={false}
        visible={show}
        onRequestClose={() => {
          console.log('click')
          setShow(!show);
        }}
      >
        <View style={{flex:1,justifyContent:'center'}}>
          <Button 
            title='隐藏Modal'
            onPress={()=>{setShow(false)}}
          />
        </View>
      </Modal>

      <FlatList 
        data={topics}
        renderItem={({item}) => <Text style={styles.text}>{item.title}</Text>}
        keyExtractor={item=>item.id}
        onRefresh={()=>{
          setRefresh(true);
          setTimeout(()=>{
            setRefresh(false);
          },3000)
          console.log(123);
        }}
        refreshing={refresh}
        onEndReached={()=>{
          page++;
          getTopics(page);
          console.log(page);
        }}
      />      
    </View>
  );
}
const styles = StyleSheet.create({
  font:{
    fontSize: 50,
    color: '#f00'
  },
  text:{
    fontSize: 30,
    marginTop: 30
  }
});
